import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import { Row, Col, Card, Form, Modal, Input, Table, Button, message, DatePicker } from 'antd';
import GeneralTableComponent from 'components/GeneralTableComponent';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

const confirm = Modal.confirm;
const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const { TextArea } = Input;

@connect(({ expenseDetail, loading }) => ({
  expenseDetail,
  loading: loading.models.expenseDetail,
}))
@Form.create()
export default class ExpenseDetail extends PureComponent {
  state = {
    paramList: {
      pageNo: 1,
      pageSize: 10,
      dateRange: [],
    },
    dialogVisible: false,
  };

  componentDidMount() {
    this.getRechargeData();
  }

  getRechargeData = () => {
    const { dispatch } = this.props;
    const { paramList } = this.state;
    let postParam = {
      pageNo: paramList.pageNo,
      pageSize: paramList.pageSize,
    };
    if (paramList.dateRange[0]) {
      [postParam.startTime, postParam.endTime] = [
        paramList.dateRange[0].format('YYYY-MM-DD HH:mm:ss'),
        paramList.dateRange[1].format('YYYY-MM-DD HH:mm:ss'),
      ];
    }
    dispatch({
      type: 'expenseDetail/fetchGetTopupList',
      payload: {
        ...postParam,
      },
    });
  };

  postRecharge = list => {
    const { dispatch, form } = this.props;
    let postParam = {
      merchantNo: parseInt(list.merchantNo),
      amount: parseInt(list.amount),
      bankCard: parseInt(list.bankCard),
      name: list.name,
      // receiveBankCard: list.receiveBankCard,
      receiveTime: list.receiveTime.format('YYYY-MM-DD HH:mm:ss'),
      remark: list.remark,
    };
    dispatch({
      type: 'expenseDetail/fetchTopupRecharge',
      payload: {
        ...postParam,
      },
      callback: res => {
        if (res.code == 200) {
          message.success(`提交成功, 充值中`);
          this.setState({
            dialogVisible: false,
          });
          form.resetFields();
        } else {
          message.error(`${res.message}`);
        }
      },
    });
  };

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { paramList } = this.state;
    paramList.pageNo = pagination.pageSize === paramList.pageSize ? pagination.current : 1;
    paramList.pageSize = pagination.pageSize;
    this.getRechargeData();
  };

  handleDateChange = (dates, dateRanges) => {
    const { paramList } = this.state;
    paramList.dateRange = dates;
    paramList.pageNo = 1;
    this.getRechargeData();
  };

  showDialog = value => {
    this.setState({
      dialogVisible: true,
    });
  };

  handleRechargeOk = () => {
    const { form } = this.props;
    form.validateFields((err, fieldsValue, ccc) => {
      let isNum = /^[0-9]*$/;
      if (
        isNum.test(fieldsValue.merchantNo) &&
        isNum.test(fieldsValue.amount) &&
        isNum.test(fieldsValue.bankCard) &&
        fieldsValue.name &&
        fieldsValue.receiveTime &&
        fieldsValue.remark
      ) {
        this.postRecharge(fieldsValue);
      }
    });
  };

  handleRechargeCancel = () => {
    this.setState({
      dialogVisible: false,
    });
  };

  formatDate(time) {
    let x = time - 0;

    let now = new Date(x);
    let year = now.getFullYear();
    let month = '0' + (now.getMonth() + 1);
    let date = '0' + now.getDate();
    let hour = '0' + now.getHours();
    let min = '0' + now.getMinutes();
    let second = '0' + now.getSeconds();
    return (
      year +
      '-' +
      month.substr(-2) +
      '-' +
      date.substr(-2) +
      ' ' +
      hour.substr(-2) +
      ':' +
      min.substr(-2) +
      ':' +
      second.substr(-2)
    );
  }

  render() {
    const { expenseDetail: { topupListData }, loading, form } = this.props;
    const { getFieldDecorator } = form;

    const tableColumns = [
      {
        title: '序号',
        dataIndex: 'demo',
        key: 'demo',
        render: (text, record, index) => {
          return (
            <span>
              {index + 1 + (topupListData.pagination.current - 1) * topupListData.pagination.size}
            </span>
          );
        },
      },
      {
        title: '提交日期',
        dataIndex: 'createTime',
        key: 'createTime',
        render: (text, record, index) => {
          return <span>{this.formatDate(text)}</span>;
        },
      },
      {
        title: '操作类型',
        dataIndex: 'demo2',
        key: 'demo2',
        render: (text, record, index) => {
          return <span>充值</span>;
        },
      },
      {
        title: '充值商户号',
        dataIndex: 'merchantNo',
        key: 'merchantNo',
        render: val => `${val}`,
      },
      {
        title: '充值方式',
        dataIndex: 'feeType',
        key: 'feeType',
        render: (text, record, index) => {
          return <span>银行汇款</span>;
        },
      },
      {
        title: '充值金额',
        dataIndex: 'amount',
        key: 'amount',
        render: val => `${val}`,
      },
      {
        title: '支付银行账户号',
        dataIndex: 'bankCard',
        key: 'bankCard',
        render: val => `${val}`,
      },
      {
        title: '支付银行账户名',
        dataIndex: 'name',
        key: 'name',
        render: val => `${val}`,
      },
      {
        title: '收款银行账号',
        dataIndex: 'receiveBankCard',
        key: 'receiveBankCard',
        render: val => `${val}`,
      },
      {
        title: '收款日期',
        dataIndex: 'receiveTime',
        key: 'receiveTime',
        render: (text, record, index) => {
          return <span>{this.formatDate(text)}</span>;
        },
      },
      {
        title: '交易备注',
        dataIndex: 'remark',
        key: 'remark',
        render: val => `${val}`,
      },
    ];

    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    };

    return (
      <PageHeaderLayout title="消费明细">
        <Card bordered={false}>
          <div style={{ marginBottom: 20 }}>
            <Button onClick={this.showDialog}>充值</Button>
          </div>

          <div style={{ marginBottom: 20 }}>
            <RangePicker allowClear onChange={this.handleDateChange} />
          </div>

          <GeneralTableComponent
            loading={loading}
            data={topupListData}
            columns={tableColumns}
            onChange={this.handleStandardTableChange}
            showSizeChanger
            rowKey={'id'}
          />
        </Card>

        <Modal
          title="充值"
          visible={this.state.dialogVisible}
          onOk={this.handleRechargeOk}
          onCancel={this.handleRechargeCancel}
        >
          <Form layout={'horizontal'}>
            <div>
              <FormItem label="所属机构" {...formItemLayout}>
                <span>天机_杭州贝和网络科技有限公司_正式接入</span>
              </FormItem>
            </div>
            <div>
              <FormItem label="充值方式" {...formItemLayout}>
                <span>银行汇款</span>
              </FormItem>
            </div>
            <div>
              <FormItem label="交易金额" {...formItemLayout}>
                {getFieldDecorator('amount', {
                  rules: [{ required: true, pattern: /^[0-9]*$/, message: '请输入正确的交易金额' }],
                })(<Input />)}
              </FormItem>
            </div>
            <div>
              <FormItem label="充值商户号" {...formItemLayout}>
                {getFieldDecorator('merchantNo', {
                  rules: [
                    { required: true, pattern: /^[0-9]*$/, message: '请输入正确的充值商户号' },
                  ],
                })(<Input />)}
              </FormItem>
            </div>
            <div>
              <FormItem label="支付银行账户号" {...formItemLayout}>
                {getFieldDecorator('bankCard', {
                  rules: [
                    { required: true, pattern: /^[0-9]*$/, message: '请输入正确的支付银行账户号' },
                  ],
                })(<Input />)}
              </FormItem>
            </div>
            <div>
              <FormItem label="支付银行账户名" {...formItemLayout}>
                {getFieldDecorator('name', {
                  rules: [{ required: true, message: '请输入支付银行账户名' }],
                })(<Input />)}
              </FormItem>
            </div>
            {/*<div>
              <FormItem label="收款银行账号" {...formItemLayout}>
                {getFieldDecorator('receiveBankCard', {
                  rules: [{ required: true, pattern: /^[0-9]*$/, message: '请输入正确的收款银行账号' }],
                })(
                  <Input />
                )}
              </FormItem>
            </div>*/}
            <div>
              <FormItem label="收款日期" {...formItemLayout}>
                {getFieldDecorator('receiveTime', {
                  rules: [{ required: true, message: '请选择收款日期' }],
                })(<DatePicker />)}
              </FormItem>
            </div>
            <div>
              <FormItem label="交易备注" {...formItemLayout}>
                {getFieldDecorator('remark', {
                  rules: [{ required: true, message: '请输入交易备注' }],
                })(<TextArea rows={4} />)}
              </FormItem>
            </div>
          </Form>
        </Modal>
      </PageHeaderLayout>
    );
  }
}
